package fasdk

import (
	"gitee.com/bupt-zkjc/fabric-sdk-go/pkg/client/ledger"
	"gitee.com/bupt-zkjc/fabric-sdk-go/pkg/common/providers/fab"
	"gitee.com/bupt-zkjc/fabric-sdk-go/pkg/fabsdk"
)

func (f *FabricClient) QueryLedger(peers []string) (*fab.BlockchainInfoResponse, error) {

	ledger, err := ledger.New(f.sdk.ChannelContext(f.ChannelId, fabsdk.WithUser(f.OrgAdmin), fabsdk.WithOrg(f.Orgs[0])))
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}

	bci, err := ledger.QueryInfo()
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	return bci, nil
}


func (f *FabricClient) QueryBlockByNumber(height uint64, peers []string) (*FabricBlock, error) {

	ledgerClient, err := ledger.New(f.sdk.ChannelContext(f.ChannelId, fabsdk.WithUser(f.OrgAdmin), fabsdk.WithOrg(f.Orgs[0])))
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}

	block, err := ledgerClient.QueryBlock(height, ledger.WithTargetEndpoints(peers...))
	bs, err := parseBlock(blockParse(block))

	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	return bs, nil
}

func (f *FabricClient) QueryBlockByHash(hash []byte, peers []string) (*FabricBlock, error) {

	ledgerClient, err := ledger.New(f.sdk.ChannelContext(f.ChannelId, fabsdk.WithUser(f.OrgAdmin), fabsdk.WithOrg(f.Orgs[0])))
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}

	block, err := ledgerClient.QueryBlockByHash(hash, ledger.WithTargetEndpoints(peers...))
	bs, err := parseBlock(blockParse(block))

	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	return bs, nil
}

func (f *FabricClient) QueryBlockByTxid(txid string, peers []string) (*FabricBlock, error) {

	ledgerClient, err := ledger.New(f.sdk.ChannelContext(f.ChannelId, fabsdk.WithUser(f.OrgAdmin), fabsdk.WithOrg(f.Orgs[0])))
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}

	block, err := ledgerClient.QueryBlockByTxID(fab.TransactionID(txid), ledger.WithTargetEndpoints(peers...))
	bs, err := parseBlock(blockParse(block))

	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	return bs, nil
}

func (f *FabricClient) QueryTransactionDetail(txid string, peers []string) (*FabricTransaction, error) {

	ledgerClient, err := ledger.New(f.sdk.ChannelContext(f.ChannelId, fabsdk.WithUser(f.OrgAdmin), fabsdk.WithOrg(f.Orgs[0])))
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}

	transaction, err := ledgerClient.QueryTransaction(fab.TransactionID(txid), ledger.WithTargetEndpoints(peers...))
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	tx, err := transactionParse(transaction.TransactionEnvelope.Payload)

	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	return tx, nil
}